﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

using System.Text.RegularExpressions;
using Windows.UI.Popups;
using System.Threading.Tasks;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace DigitalPublisher
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public string isifile;
        public string fullPage = "";
        public string MainHtml;
        public int jmlHtml;
        string tmp;
        bool cek;
        FolderPicker folderPicker;
        IReadOnlyList<StorageFile> files;


        RegexClass reg = new RegexClass();
        public MainPage()
        {
            this.InitializeComponent();
            
        }


        private async void OKbtn_Click(object sender, RoutedEventArgs e)
        {
            folderPicker = new FolderPicker();
            folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            folderPicker.FileTypeFilter.Add(".html");
            folderPicker.FileTypeFilter.Add(".png");
            folderPicker.FileTypeFilter.Add(".jpg");
            folderPicker.FileTypeFilter.Add(".css");
            folderPicker.FileTypeFilter.Add(".js");
            StorageFolder folder = await folderPicker.PickSingleFolderAsync();
            if (folder != null) 
            {
                StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
                folderNameText.Text = "Picked folder: " + folder.Name;
                files = await folder.GetFilesAsync();
                
            }
            else
            {
                folderNameText.Text = "Operation cancelled.";
            }
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            getList();   
        }

       

        private async void ReadFile()
        {
            Uri uri = new Uri("ms-appx:///"+tmp);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
            MainHtml = await FileIO.ReadTextAsync(file); //reading content as string
        }

        public void BodyReplace(string pages)
        {

            fullPage += "<div class=\"bb-item\" id=\"item" + jmlHtml + "\">\n";
            fullPage += "<div class=\"content\">\n";
            fullPage += "<div class=\"scroller\">\n";
            fullPage += "<h2>Judul" + jmlHtml + "</h2>\n";
            fullPage +=  pages + "\n";
            fullPage += "</div></div></div>";

        }

        
        private async void GenerateBtn_Click(object sender, RoutedEventArgs e)
        {
            reg.listPathImage.Clear();
            reg.listNamaImage.Clear();
            reg.listPathBody.Clear();
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
            StorageFolder digipub = null;
            var localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            try
            {
                digipub = await storageFolder.GetFolderAsync("digipup");

            }
            catch
            {
                storageFolder.CreateFolderAsync("digipup");
             }
            
            StorageFolder destinationFolder = await digipub.CreateFolderAsync(newFileNameTb.Text);
            
            string NewFileName = newFileNameTb.Text + ".html";

            int count = 0;
            string fileasli = "";
                ReadFile();
            foreach (StorageFile file in files)
            {
                Standart standart = new Standart();
                if (file.FileType == ".html" || file.FileType == ".htm")
                {
                    jmlHtml = count + 1;
                    fileasli = await FileIO.ReadTextAsync(file);
                    reg.HeadRegex(fileasli); 
                    reg.BodyRegex(fileasli);
                    reg.StyleRegex(fileasli);
                    reg.LinkRegex(fileasli);
                    BodyReplace(reg.listPathBody[count]);
                    
                    //isifile = MainHtml;

                    isifile += reg.listPathBody[count];
                    reg.listBodyPage.Add(isifile);
                    count = count + 1;

                }
            }

            reg.ImgRegex(isifile);
            foreach (StorageFile file in files)
            {
                if (file.FileType == ".jpg" || file.FileType == ".png")
                {
                    
                    for (int i = 0; i < reg.listNamaImage.Count; i++)
                    {
                        if (file.Name == reg.listNamaImage[i])
                        {
                            Base64 conv = new Base64();
                            conv.GetBtyeFromFile(file);

                            await Task.Delay(50);
                            fullPage = fullPage.Replace(reg.listPathImage[i], "data:image/png;base64," + conv.base64);


                            

                        }
                    }
                }
            }
            foreach (StorageFile file in files)
            {
                if (file.FileType == ".css")
                {
                    for (int i = 0; i < reg.listNamaStyle.Count; i++)
                    {
                        if (file.Name == reg.listNamaStyle[i])
                        {
                            string style = await FileIO.ReadTextAsync(file);
                            reg.stylefile += style;
                        }
                    }
                }
            }

            reg.ScriptRegex(reg.listHeadPage.ToString());
            reg.LinkScriptRegex(reg.listHeadPage.ToString());
            reg.LinkScriptRegex(isifile);
            foreach (StorageFile file in files)
            {
                if (file.FileType == ".js")
                {
                    for (int i = 0; i < reg.listNamaScript.Count; i++)
                    {
                        if (file.Name == reg.listNamaScript[i])
                        {
                            string script = await FileIO.ReadTextAsync(file);
                            reg.scriptfile += script;
                        }
                        else
                        {
                            string script = await FileIO.ReadTextAsync(file);
                            reg.scriptlinkfileDown += script;
                        }
                    }
                }
            
            }
        
            MainHtml = MainHtml.Replace("IsiStyle", reg.stylefile);
            MainHtml = MainHtml.Replace("IsiScript", reg.scriptfile);
            MainHtml = MainHtml.Replace("IsiScrDw", reg.scriptlinkfileDown);
            MainHtml = MainHtml.Replace("IsiHtml", fullPage);
            StorageFile newfile = await destinationFolder.CreateFileAsync(NewFileName);
            await Windows.Storage.FileIO.WriteTextAsync(newfile, MainHtml);
            

            this.Frame.Navigate(typeof(ViewPage), MainHtml);
        }

        private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
        {
            tmp = "index.html";
            cek = true;
        }

        private void radiobtnno_Checked(object sender, RoutedEventArgs e)
        {
            tmp = "index2.html";
            cek = false;
        }

        private async void getList()
        {
            List<string> listItem = new List<string>();
            IReadOnlyList<StorageFolder> digipups;
            StorageFolder digipub = await KnownFolders.DocumentsLibrary.GetFolderAsync("digipup");

            digipups = await digipub.GetFoldersAsync();

            foreach (StorageFolder fol in digipups)
            {
                listItem.Add(fol.Name);

            }
            
            ListView1.ItemsSource = listItem;
        }
        

    }
}
